package rctgl.util;

import java.util.*;
import java.io.*;

public class RLEDecoder
{
	
	
	public static byte [] decodeRLE( byte [] srcBytes )
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream( srcBytes.length );
		
		byte curByte;
		int off=0;
		
		while(off < srcBytes.length - 4)
		{
			curByte =  srcBytes[off++];
			String byteStr = Integer.toBinaryString(curByte);
			
			if((curByte & 0x80) == 0)
			{
				int targetLength = curByte;
				for(int i=0; i<=targetLength; i++)
					baos.write( srcBytes[off++] );
				
			}
			else
			{
				byte byteToCopy = srcBytes[off++];
				int targetLength = (curByte * -1);
				
				for(int i=0; i<=targetLength; i++)
					baos.write( byteToCopy );
				
			}
		}
		
		for(int i=0; i<4; i++)
			baos.write( srcBytes[off++] );
		
		
		
		
		return baos.toByteArray();
		
		
	}

}
